package bupt.party.online.video;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import bupt.party.online.util.DateUtil;

public class VideoMgr {
	private static VideoMgr instance;
	public static final String WEBSITE_NAME = "bpol-1.0";

	public static VideoMgr getInstance() {
		if (instance == null) {
			synchronized (VideoMgr.class) {
				if (instance == null) {
					instance = new VideoMgr();
				}
			}
		}
		return instance;
	}
	
	private VideoMgr(){
		try {
			this.updateVideos();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
//	private VideoMap _videoMap = new VideoMap();
	private IVideoPool _videoPool = new VideoPool();
	private int count = 0;
	
	public void updateVideos() throws FileNotFoundException, IOException{
		_videoPool.clear();
		
		String videoRootPath = System.getProperty("user.dir");
		File videoFolder = new File( videoRootPath + "/videos");
		if(!videoFolder.exists()){
			videoFolder = new File( videoRootPath + "/src/main/webapp/videos");
			if(!videoFolder.exists()){
				String videoHome = System.getenv("VIDEO_HOME") + "/webapps";
				videoFolder = new File(videoHome + "/videos");
				if(!videoFolder.exists()){
					videoFolder = new File(videoHome + "/" + WEBSITE_NAME + "/videos");
				}
			}
		}
		videoRootPath = videoFolder.getAbsolutePath();
		loadFolderData(videoFolder, videoRootPath);
	
		_videoPool.updateSortedVideoMap();
	}
	
	/**
	 * The file is a folder
	 * @param folder
	 * @throws IOException 
	 */
	private void loadFolderData(File folder, final String videoRootPath) throws IOException{
		if(folder == null || folder.list().length == 0){
			return;
		}
		
		int videoRootPathLength = videoRootPath.length();
		String curFolderPath = folder.getAbsolutePath();
		String prefixPath = curFolderPath.substring(videoRootPathLength);
		prefixPath = prefixPath.replace("\\", "/");
		
		Map<String, String> propMap = new HashMap<String, String>();
		Map<String, String> picMap = new HashMap<String, String>();
		Map<String, String> videoMap = new HashMap<String, String>();

		File[] subFiles = folder.listFiles();
		for (int i = 0; i < subFiles.length; i++) {
			if(subFiles[i].getName().startsWith(".")){
				continue;
			}
			if(subFiles[i].isDirectory()){
				loadFolderData(subFiles[i], videoRootPath);
				continue;
			}
			
			String str = subFiles[i].getName();
			String[] items = str.split("\\.");
			if (items[1].equals("jpg") || items[1].equals("gif")
					|| items[1].equals("png")) {
				picMap.put(items[0], str);
				
			} else if (items[1].equals("mp4") || items[1].equals("flv")) {
				videoMap.put(items[0], str);
				
			} else if (items[1].equals("txt") || items[1].equals("properties")) {
				propMap.put(items[0], str);
				
			}
		}

		Iterator<String> iter = videoMap.keySet().iterator();
		while(iter.hasNext()){
			String name = iter.next();	// video2
			String picPath = picMap.get(name);
			String propPath = propMap.get(name);
			
			Video item = new Video();
			item.setVideopath( prefixPath + "/" + videoMap.get(name));
			
			// Set the default pic if picName is null
			if(picPath == null){
				picPath = "/" + Video.DEFAULT_PIC;
			}else{
				picPath =  prefixPath + "/" + picPath;
			}
			item.setPicPath(picPath);
			
			Properties propFile = new Properties();
			if(propPath == null){
				propFile.setProperty(Video.VIDEO_ID, prefixPath + "/" + videoMap.get(name));
				try {
					Thread.sleep(2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				propFile.setProperty(Video.UPLOAD_DATE, DateUtil.Date2DefaultStr(Calendar.getInstance().getTime()));
				propFile.setProperty(Video.COUNT, "0");
				propFile.setProperty(Video.STATUS, Video.STATUS_UNEDITED);
				propFile.setProperty(Video.CATEGORY_ID, prefixPath);
				FileOutputStream fos = new FileOutputStream(curFolderPath + "/" + name + ".properties");
				propFile.store(fos, "");
			}else{
				propFile.load(new FileInputStream( curFolderPath + "/" + propPath));
			}
			item.setProps(propFile);

			_videoPool.addVideo(item);
		}
	}
	
	private void innerUpdate(){
		count = ++count % 20;
		if(count == 0){
			try {
				this.updateVideos();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public List<Video> getVideosByCategoryId(String categoryId){
		innerUpdate();
		return _videoPool.getVideosByCategoryId(categoryId);
	}
	
	public List<Video> getVideosByStatus(String status) {
		innerUpdate();
		return _videoPool.getVideosByStatus(status);
	}
	
	public List<Video> getVideos(String categoryId, String status) {
		innerUpdate();
		return _videoPool.getVideos(categoryId, status);
	}
	
	public List<Video> getAllVideos(){
		innerUpdate();
		return _videoPool.getAllVideos();
	}
	
	public boolean updateVideoInfo(String videoId, String categoryId, String name, String picPath, String introduction, String videoStatus1){
		boolean flag = _videoPool.updateVideoInfo(videoId, categoryId, name,  picPath, introduction, videoStatus1);
		try {
			this.updateVideos();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	public Video getVideo(String videoPic){
		return _videoPool.getVideo(videoPic);
	}
	
	public boolean swapVideosUploadDate(String videoPath1, String videoPath2){
		return _videoPool.swapVideosUploadDate(videoPath1, videoPath2);
	}
	
	/**
	 * 移动若干个一个位置
	 * @param step
	 * @return
	 */
	public boolean moveStep(String videoPath, int step){
		return _videoPool.moveStep(videoPath, step);
	}
	
	public Video getLastestVideo() {
		return _videoPool.getLastestVideo();
	}

	public List<Video> getHotestVideos() {
		return _videoPool.getHotestVideos();
	}
	
	public List<Video> getLastest3Video(){
		return _videoPool.getLastest3Video();
	}
	
	public static void main(String[] args) {
		VideoMgr mgr = VideoMgr.getInstance();
//		mgr.updateVideoInfo("/videos/video1.mp4", "0101", "abc", null, "德芙", "2");
//		List<Video> list = mgr.getAllVideos();
//		for(int i = 0; i < list.size(); i++){
//			//System.out.println(list.get(i).getProps().getProperty(Video.VIDEO_ID));
//			System.out.println("picPath: " + list.get(i).getPicPath());
//		}
		List<Video> l3v = mgr.getLastest3Video();
		Iterator<Video> iter = l3v.iterator();
//		while(iter.hasNext()){
//			System.out.println(iter.next().getVideopath());
//		}
		
//		System.out.println(mgr.getLastest3Video().size());
		
//		mgr.swapVideosUploadDate("/videos/bput.flv", "/videos/buaa.flv");
//		list = mgr.getAllVideos();
//		for(int i = 0; i < list.size(); i++){
//			//System.out.println(list.get(i).getProps().getProperty(Video.UPLOAD_DATE));
//		}
		
//		String path = System.getenv("CATALINA_BASE");
//		System.out.println("path: " + path);
//		System.out.println(System.getProperty("CATALINA_BASE"));
		
	}
}
